package demo2;


import java.util.Arrays;

public class MyStack {
    int[] elem;
    int usedSize; // 使用usedSize来记录栈的有效数字
    //这里通过构造方法来给数组初始化
    //初始化长度设置为5
    public MyStack() {
        elem = new int[5];
    }

    //入栈
    public void push(int val) {
        if (isFull()) {
            //如果满了  就给它进行2倍扩容
            this.elem = Arrays.copyOf(this.elem, this.elem.length * 2);
        }
        this.elem[usedSize++] = val;
    }

    //出栈
    public int pop() {
        if (isEmpty()) {
            //如果空 就抛异常
            throw new RuntimeException("栈为空");
        }
        int oldVal = this.elem[--usedSize];
        return oldVal;
    }

    //获得栈顶元素
    public int peek() {
        if (isEmpty()) {
            //如果空 就抛异常
            throw new RuntimeException("栈为空");
        }
        return this.elem[usedSize - 1];
    }

    //判断是不是空
    public boolean isEmpty() {
        return this.usedSize == 0;
    }

    //判断栈(数组)有没有满
    public boolean isFull() {
        return usedSize == this.elem.length;
    }
}
